import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import os
file_path = r'd:\组队你组不组\team-up-do-you-want-to-group1\project\练习一\FhjlViewDD.xlsx'
if not os.path.exists(file_path):
    raise FileNotFoundError(f'Excel文件不存在: {file_path}')

# 读取Excel文件
df = pd.read_excel(r'd:\组队你组不组\team-up-do-you-want-to-group1\project\练习一\FhjlViewDD.xlsx')

# 设置列名
date_column = '创建时间'
quantity_column = '净重'
location_column = '发货地'  # 假设发货地信息存储在'发货地'列

# 筛选6月份数据
df[date_column] = pd.to_datetime(df[date_column])
june_data = df[df[date_column].dt.month == 6]

# 按发货地统计6月份货运总量
location_stats = june_data.groupby(location_column)[quantity_column].sum().sort_values(ascending=False)

# 打印统计结果
print('6月份各发货地货运总量统计:')
print(location_stats)

# 创建子母图
fig = plt.figure(figsize=(14, 12))

# 主图 - 显示主要数据
ax1 = fig.add_axes([0.1, 0.1, 0.7, 0.8])
# 明确指定主图显示的三个地点
main_locations = ['武新一期', '武新二期', '金盛兰']
main_data = location_stats[location_stats.index.isin(main_locations)]
other_data = location_stats[~location_stats.index.isin(main_locations)]

wedges_main, texts_main, autotexts_main = ax1.pie(
    main_data,
    autopct='%1.1f%%',
    startangle=90,
    counterclock=False,
    colors=plt.cm.Paired.colors[:len(main_data)],
    wedgeprops={'linewidth': 1, 'edgecolor': 'white'},
    pctdistance=0.8,
    textprops={'fontsize': 12, 'color': 'black'}
)
ax1.set_title('6月份主要发货地货运量占比', fontsize=16, pad=10)

# 为小占比数据添加一个汇总区块
if len(other_data) > 0:
    wedges_main, texts_main, autotexts_main = ax1.pie(
    [*main_data, other_data.sum()],
    labels=[*main_data.index, '其他小占比'],
    autopct=lambda p: '小占比' if p < 2 else f'{p:.1f}%',
    startangle=90,
    counterclock=False,
    colors=[*plt.cm.Paired.colors[:len(main_data)], 'lightgray'],
    wedgeprops={'linewidth': 1, 'edgecolor': 'white'},
    pctdistance=0.7,
    textprops={'fontsize': 10, 'color': 'black'}
)
    
    # 子图 - 放大显示小占比数据
    ax2 = fig.add_axes([0.7, 0.3, 0.3, 0.4])
    wedges_sub, texts_sub, autotexts_sub = ax2.pie(
        other_data,
        autopct=lambda p: f'{p:.1f}%\n{other_data.index[np.argmin(np.abs(other_data - p/100*sum(other_data)))]}',
        startangle=90,
        counterclock=False,
        colors=plt.cm.Paired.colors[len(main_data):len(main_data)+len(other_data)],
        wedgeprops={'linewidth': 1, 'edgecolor': 'white'},
        textprops={'fontsize': 10, 'color': 'black'}
    )
    
    
    ax2.set_title('小占比发货地详情', fontsize=12, pad=10)

plt.tight_layout(pad=1.08, h_pad=None, w_pad=None, rect=None)

# 设置中文字体
plt.rcParams['font.sans-serif'] = ['SimHei', 'Microsoft YaHei', 'Arial Unicode MS']
plt.rcParams['axes.unicode_minus'] = False

# 确保目录存在并保存图像
output_dir = r'e:\组队你组不组\team-up-do-you-want-to-group1\project\练习一\output'
os.makedirs(output_dir, exist_ok=True)
plt.savefig(os.path.join(output_dir, '6月份各发货地货运量占比.png'))
plt.show()

# 将结果保存到CSV文件
output_path = os.path.join(output_dir, '6月份各发货地货运量统计.csv')
location_stats.to_csv(output_path, encoding='utf-8-sig')
print(f'统计结果已保存到: {output_path}')